<?php

class Users_ConfirmAction extends SrsUsersBaseAction
{
	public function isSecure()
	{
		return false;
	}
	
	public function executeRead(AgaviRequestDataHolder $rd)
	{
		if ($rd->hasParameter('key'))
		{
			return $this->executeWrite($rd);
		}

		return 'Input';
	}

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$user = Doctrine_Query::create()
		        ->from('User')
			      ->where('email=?', $rd->getParameter('user'))
					  ->fetchOne();

		if (empty($user))
		{
			$this->addError('wrong_email', 'user', 'Nieprawidłowy adres e-mail.');

			return 'Error';
		}

		if (empty($user->confirmKey))
		{
			$this->addError('already_active', 'user', 'Konto z danym adresem e-mail jest już aktywne.');

			return 'Error';
		}

		if (strtolower($user->confirmKey) != strtolower($rd->getParameter('key')))
		{
			$this->addError('wrong_key', 'key', 'Nieprawidłowy klucz potwierdzenia.');

			return 'Error';
		}

    $user->active     = true;
		$user->confirmKey = '';
		$user->save();

		$this->getContext()->getUser()->login($user->email, $user->password, true);

		return 'Success';
	}
}